package com.shixun.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shixun.domain.Leaves;
import com.shixun.service.LeaveService;
import com.shixun.utils.R;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/leaves")
public class LeaveController {
    @Autowired
    LeaveService leaveService;

    /**
     * 所有请假信息
     * @param pageSize
     * @param pageNum
     * @param sname
     * @param sno
     * @return
     */
    @GetMapping("/page")
    public R helperPage(int pageSize, int pageNum, String sname, String sno){
        R r = leaveService.leavePage(pageSize, pageNum, sname, sno);
        return r;
    }

    /**
     * 删除请假信息
     * @param id
     * @return
     */
    @DeleteMapping("/del/{id}")
    public R deleteLeave(@PathVariable Long id){
        leaveService.removeById(id);
        return new R(200,"删除成功",null);
    }

    /**
     * 个人请假信息
     * @return
     */
    @GetMapping("/sLPage")
    public  R sLPage(int pageSize, int pageNum,@Param("sid") Long sid){
        Page<Leaves> page=new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Leaves> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Leaves::getSid,sid);
         leaveService.page(page, queryWrapper);
        return new R(200,"",page);
    }

    /**
     * 修改请假信息
     * @param leaves
     * @return
     */
    @PutMapping("/update")
    public R updateLeave(@RequestBody Leaves leaves){
        if(leaves.getBeginTime()==null || leaves.getEndTime()==null){
                    return new R(500,"开始和结束时间都不为空",null);
       }
       if(leaves.getBeginTime().after(leaves.getEndTime())){//开始时间大于结束时间
                    return new R(500,"开始时间不能大于结束时间，数据不合法",null);
         }

            leaveService.updateById(leaves);
            return new R(200,"修改成功",null);

    }

    /**
     * 学生请假
     * @param leaves
     * @return
     */
    @PostMapping("/add")
    public R addLeave(@RequestBody Leaves leaves){

        if(leaves.getBeginTime()==null || leaves.getEndTime()==null){
            return new R(500,"开始和结束时间都不为空",null);
        }
        if(leaves.getBeginTime().after(leaves.getEndTime())){//开始时间大于结束时间
            return new R(500,"开始时间不能大于结束时间，数据不合法",null);
        }
        //查询该学生这条请假信息的开始时间要大于历史请假的结束时间
        LambdaQueryWrapper<Leaves> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Leaves::getSid, leaves.getSid());
        queryWrapper.ge(Leaves::getEndTime, leaves.getBeginTime());
        int count = leaveService.count(queryWrapper);
        if(count==0){//没有查到，插入数据
            leaveService.save(leaves);
            return new R(200,"添加成功",null);
        }
        return new R(500,"该段时间内有请假或者你输入的日期是以前的日期",null);

    }

}
